package com.nami.common.utils;

import com.alibaba.fastjson2.JSON;
import com.nami.common.constants.ServletConstants;
import com.nami.common.constants.SystemConstants;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Servlet 工具类
 *
 * @author chengh
 */
public class ServletUtils {

    /**
     * 获取 HttpServletResponse 对象
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        return servletRequestAttributes.getResponse();
    }

    /**
     * Response 对象写出数据
     *
     * @param msg 消息数据
     * @throws IOException IO异常
     */
    public static void write(String msg) throws IOException {
        HttpServletResponse response = getResponse();
        response.setHeader(ServletConstants.Header.CONTENT_TYPE, ServletConstants.JSON_UTF8);
        response.setCharacterEncoding(SystemConstants.UTF8);
        response.getWriter().write(msg);
    }

    /**
     * Response 对象JSON写出数据
     *
     * @param data 数据
     * @throws IOException IO异常
     */
    public static void writeJson(Object data) throws IOException {
        write(JSON.toJSONString(data));
    }

    /**
     * 判断是否为 Ajax 请求
     * @param request HttpServletRequest
     * @return 判断是不是ajax请求
     */
    public static Boolean isAjax(HttpServletRequest request) {
        String requestType = request.getHeader(ServletConstants.Header.X_REQUESTED_WITH);
        return ServletConstants.Header.XML_HTTP_REQUEST.equals(requestType);
    }

}
